package analyse

import (
	"github.com/shopspring/decimal"
	"github.com/yejingxuan/accumulate/interface/dto"
	"math"
)

//ai分析器
type AIAnalyzerInterface interface {
	DataClean(resp dto.KlineDataResp) []BaseAnalyseInfo //数据清洗
	CalculateTag([]BaseAnalyseInfo) []string            //标签计算
}

//ai分析器实现
type aiAnalyzer struct {
}

func NewAIAnalyzer() *aiAnalyzer {
	return &aiAnalyzer{}
}

//数据清洗
func (a aiAnalyzer) DataClean(data dto.KlineDataResp) []BaseAnalyseInfo {
	MA60Line := make([]float64, 0)
	closeLine := make([]float64, 0)
	baseInfos := make([]BaseAnalyseInfo, 0)

	for _, dayInfo := range data.Data.Item {
		closeData := dayInfo[5] //shou pan price
		closeLine = append(closeLine, closeData)
	}

	for i := 0; i < len(closeLine)-60; i++ {
		closeData := closeLine[i : i+60]
		ma60 := CalculateAvg(closeData)
		MA60Line = append(MA60Line, ma60)

		dayInfo := data.Data.Item[i+60]
		baseInfos = append(baseInfos, BaseAnalyseInfo{
			//Day:dayInfo[0],
			MA60:    ma60,
			Open:    dayInfo[2],
			Close:   dayInfo[5],
			Volume:  dayInfo[1],
			Percent: dayInfo[7],
		})
	}
	return baseInfos
}

//标签计算
func (a aiAnalyzer) CalculateTag(infos []BaseAnalyseInfo) []string {
	tags := make([]string, 0)
	for tag, method := range CalculateTags {
		if res := method(infos); res {
			tags = append(tags, tag.Value)
		}
	}
	return tags
}

//计算平均数
func CalculateAvg(data []float64) float64 {
	var total float64
	for _, item := range data {
		total += item
	}
	res := decimal.NewFromFloat(total).Div(decimal.NewFromFloat(float64(len(data))))
	f, _ := res.Float64()
	return math.Trunc(f*1e2+0.5) * 1e-2
}

type BaseAnalyseInfo struct {
	Day     string  `json:"day"`
	MA60    float64 `json:"MA60"`
	Open    float64 `json:"open"`    //开盘价
	Close   float64 `json:"close"`   //收盘价
	Volume  float64 `json:"volume"`  //当日成交量
	Percent float64 `json:"percent"` //当日涨跌幅
}
